package com.backend.system.service.processors.menu;

import com.backend.system.beans.menu.GrantMenusToRoleReq;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.MenuRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色分配菜单处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.ROLE_GRANT_MENUS)
public class GrantMenusToRoleProcessor extends AbstractProcessorTemplate<GrantMenusToRoleReq, Boolean> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<GrantMenusToRoleReq> context) {
        GrantMenusToRoleReq req = context.getData();
        Long roleId = req.getRoleId();
        List<Long> menuIds = req.getMenuIds();

        // 先删除角色对应的所有菜单列表
        menuRoleService.removeAllByRoleId(roleId);

        // 批量新增菜单角色数据
        List<MenuRole> menuRoles = new ArrayList<>();
        for (Long menuId : menuIds) {
            MenuRole menuRole = new MenuRole();
            menuRole.setMenuId(menuId);
            menuRole.setRoleId(roleId);
            menuRoles.add(menuRole);
        }

        return menuRoleService.saveBatch(menuRoles);
    }
}
